const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');

// 获取横幅列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      position,
      is_active 
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];
    
    if (position) {
      whereClause += ' AND b.position = ?';
      params.push(position);
    }
    
    if (is_active !== undefined) {
      whereClause += ' AND b.is_active = ?';
      params.push(is_active === 'true');
    }
    
    // 查询总数
    const [countResult] = await db.execute(
      `SELECT COUNT(*) as total FROM banners b ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        b.id,
        b.title,
        b.description,
        b.image_url,
        b.link_url,
        b.position,
        b.sort_order,
        b.is_active,
        b.created_at,
        b.updated_at
      FROM banners b
      ${whereClause}
      ORDER BY b.sort_order ASC, b.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.execute(query, [...params, limit, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        title: row.title,
        description: row.description,
        image_url: row.image_url,
        link_url: row.link_url,
        position: row.position,
        sort_order: row.sort_order,
        is_active: row.is_active,
        createdAt: row.created_at,
        updatedAt: row.updated_at
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          pageCount: Math.ceil(total / parseInt(pageSize)),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取横幅列表失败:', error);
    res.status(500).json({ error: '获取横幅列表失败' });
  }
});

module.exports = router;